{% extends 'base.html' %}
{% load common_tags %}
{% load static %}
{% load i18n %}

{% block custom_head_css_js %}
    <style>
    .table.node_edit {
        margin-bottom: 0;
    }
    </style>
{% endblock %}

{% block content %}
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="panel-options">
                        <ul class="nav nav-tabs">
                            <li>
                                <a href="{% url 'assets:system-user-detail' pk=system_user.id %}" class="text-center"><i class="fa fa-laptop"></i> {% trans 'Detail' %} </a>
                            </li>
                            <li class="active">
                                <a href="{% url 'assets:system-user-asset' pk=system_user.id %}" class="text-center">
                                <i class="fa fa-bar-chart-o"></i> {% trans 'Asset list' %}
                                </a>
                            </li>
                            {% if system_user.username_same_with_user  %}
                            <li>
                                <a href="{% url 'assets:system-user-user' pk=system_user.id %}" class="text-center">
                                <i class="fa fa-bar-chart-o"></i> {% trans 'User list' %}
                                </a>
                            </li>
                            {% endif %}
                        </ul>
                    </div>
                    <div class="tab-content">
                        <div class="col-sm-8" style="padding-left: 0;">
                            <div class="ibox float-e-margins">
                                <div class="ibox-title">
                                    <span style="float: left"><b>{{ system_user.name }} </b><span class="badge">{{ paginator.count }}</span></span>
                                    <div class="ibox-tools">
                                        <a class="collapse-link">
                                            <i class="fa fa-chevron-up"></i>
                                        </a>
                                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                                            <i class="fa fa-wrench"></i>
                                        </a>
                                        <ul class="dropdown-menu dropdown-user">
                                        </ul>
                                        <a class="close-link">
                                            <i class="fa fa-times"></i>
                                        </a>
                                    </div>
                                </div>
                                <div class="ibox-content">
                                    {% include 'assets/_asset_user_list.html' %}
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-4" style="padding-left: 0;padding-right: 0">
                            <div class="panel panel-primary">
                                <div class="panel-heading">
                                    <i class="fa fa-info-circle"></i> {% trans 'Quick update' %}
                                </div>
                                <div class="panel-body">
                                    <table class="table">
                                        <tbody>
                                        <tr class="no-borders-tr">
                                            <td width="50%">{% trans 'Test assets connective' %}:</td>
                                            <td>
                                                <span style="float: right">
                                                    <button type="button" class="btn btn-primary btn-xs btn-test-connective" style="width: 54px">{% trans 'Test' %}</button>
                                                </span>
                                            </td>
                                        </tr>
                                        {% if system_user.auto_push %}
                                        <tr>
                                            <td width="50%">{% trans 'Push system user now' %}:</td>
                                            <td>
                                                <span style="float: right">
                                                    <button type="button" class="btn btn-primary btn-xs btn-push" style="width: 54px">{% trans 'Push' %}</button>
                                                </span>
                                            </td>
                                        </tr>
                                        {% endif %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="panel panel-info">
                                <div class="panel-heading">
                                    <i class="fa fa-info-circle"></i> {% trans 'Assets' %}
                                </div>
                                <div class="panel-body">
                                    <table class="table" id="add-assets">
                                        <tbody>
                                        <form>
                                            <tr>
                                                <td colspan="2" class="no-borders">
                                                    <select data-placeholder="{% trans 'Select assets' %}" id="id_assets" class="assets-select2 select2" style="width: 100%" multiple="" tabindex="4">
                                                    </select>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2" class="no-borders">
                                                    <button type="button" class="btn btn-info btn-sm" id="btn-add-to-assets">{% trans 'Confirm' %}</button>
                                                </td>
                                            </tr>
                                        </form>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="panel panel-info">
                                <div class="panel-heading">
                                    <i class="fa fa-info-circle"></i> {% trans 'Nodes' %}
                                </div>
                                <div class="panel-body">
                                    <table class="table node_edit" id="add-asset2group">
                                        <tbody>
                                        <form>
                                            <tr>
                                                <td colspan="2" class="no-borders">
                                                    <select data-placeholder="{% trans 'Select nodes' %}" id="node_selected" class="nodes-select2" style="width: 100%" multiple="" tabindex="4">
                                                    </select>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="2" class="no-borders">
                                                    <button type="button" class="btn btn-info btn-sm" id="btn-add-to-node">{% trans 'Confirm' %}</button>
                                                </td>
                                            </tr>
                                        </form>
                                        <table class="table" id="node_list_table">
                                        </table>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    {% include 'assets/_asset_list_modal.html' %}
{% endblock %}
{% block custom_foot_js %}
<script>
var assetsRelationUrl = "{% url 'api-assets:system-users-assets-relation-list' %}";
var nodesRelationUrl = "{% url 'api-assets:system-users-nodes-relation-list' %}";

function getRelationUrl(type) {
    var theUrl = "";
    switch (type) {
        case "asset":
            theUrl = assetsRelationUrl;
            break;
        case "node":
            theUrl = nodesRelationUrl;
            break;
    }
    return theUrl;
}

function addObjects(objectsId, type, success, fail) {
    if (!objectsId || objectsId.length === 0) {
        return
    }
    var theUrl = getRelationUrl(type);
    var body = [];
    objectsId.forEach(function (v) {
        var data = {systemuser: "{{ object.id }}"};
        data[type] = v;
        body.push(data)
    });
    if (!success) {
        success = reloadPage
    }
    var option = {
        url: theUrl,
        body: JSON.stringify(body),
        method: "POST",
        success: success,
    };
    if (fail) {
        option.error = fail;
    }
    requestApi(option)
}


function removeObject(objectId, type, success) {
    if (!objectId)  {
        return
    }
    var theUrl = getRelationUrl(type);
    theUrl = setUrlParam(theUrl, 'systemuser', "{{ object.id }}");
    theUrl = setUrlParam(theUrl, type, objectId);
    if (!success) {
        success = reloadPage
    }
    requestApi({
        url: theUrl,
        method: "DELETE",
        success: success
    });
}

function initNodeTable() {
    var theUrl = setUrlParam(nodesRelationUrl, "systemuser", "{{ object.id }}");
    var options = {
        ele: $('#node_list_table'),
        toggle: true,
        columnDefs: [
             {targets: 1, createdCell: function (td, cellData) {
                  var removeBtn = '<button class="btn btn-danger pull-right btn-xs btn-remove-from-node" data-uid="UID" type="button"><i class="fa fa-minus"></i></button>'
                      .replace('UID', cellData);
		  		  $(td).html(removeBtn);
             }}
        ],
        ajax_url: theUrl,
        dom: "trp",
        hideDefaultDefs: true,
        columns: [
            {data: "node_display", orderable: false},
            {data: "node", orderable: false},
        ],
    };
    table = jumpserver.initServerSideDataTable(options);
    return table
}


$(document).ready(function () {
	$('.select2').select2();
    nodesSelect2Init(".nodes-select2");
    initAssetTreeModel('#id_assets');
	var assetUserListUrl = setUrlParam(defaultAssetUserListUrl, "prefer_id", "{{ system_user.id }}");
	assetUserListUrl = setUrlParam(assetUserListUrl, "prefer", "system_user");
    initAssetUserTable({
        assetUserListUrl: assetUserListUrl,
        needPush: true
    });
    initNodeTable();
})
.on('click', '.btn-remove-from-node', function() {
    var $this = $(this);
    var nodeId = $(this).data('uid');
    var success = function() {
        var $tr = $this.closest('tr');
        $tr.remove();
    };
    removeObject(nodeId, "node", success)
})
.on('click', '#btn-add-to-node', function() {
    var nodes = $("#node_selected").val();
    addObjects(nodes, "node");
})
.on('click', '#btn-add-to-assets', function () {
    var assets = $("#id_assets").val();
    var options = $("#id_assets").find(":selected");
    var failed = function(s, data) {
        var invalidIndex = [];
        var validIndex = [];
        $.each(data, function (k, v) {
            if (isEmptyObject(v)) {
                validIndex.push(k)
            } else {
                invalidIndex.push(k)
            }
        });
        var invalidLabel = [];
        $.each(invalidIndex, function (k, v) {
            invalidLabel.push(options[v].text)
        });
        var errorMsg = "{% trans 'Have existed: ' %}";
        errorMsg += invalidLabel.join(", ");
        toastr.error(errorMsg)
    };
    addObjects(assets, "asset", null, failed);
})
.on('click', '.btn-push', function () {
    var theUrl = "{% url 'api-assets:system-user-task-create' pk=system_user.id %}";
    var error = function (data) {
        alert(data)
    };
    var success = function (data) {
        var taskId = data.task;
        showCeleryTaskLog(taskId);
    };
    var data = {
        action: 'push'
    };
    requestApi({
        url: theUrl,
        error: error,
        data: data,
        method: 'POST',
        success: success
    });
})
.on('click', '.btn-push-auth', function () {
    var $this = $(this);
    var assetId = $this.data('asset');
    var username = $this.data("username");
    var theUrl = "{% url 'api-assets:system-user-task-create' pk=object.id %}?username=" + username;
    var data = {
        action: 'push',
        asset: assetId,
    };
    var success = function (data) {
        var taskId = data.task;
        showCeleryTaskLog(taskId);
    };
    var error = function (data) {
        alert(data)
    };
    requestApi({
        url: theUrl,
        method: 'POST',
        data: data,
        success: success,
        flash_message: false,
        error: error
    })
})
.on('click', '.btn-test-connective', function () {
    var theUrl = "{% url 'api-assets:system-user-task-create' pk=system_user.id %}";
    var error = function (data) {
        alert(data)
    };
    var success = function (data) {
        var taskId = data.task;
        showCeleryTaskLog(taskId);
    };
    requestApi({
        url: theUrl,
        data: {action: "test"},
        error: error,
        method: 'POST',
        success: success,
        flash_message: false,
    });
})
</script>
{% endblock %}
